<template>
  <div class="market-equipment-page">
    <!-- 顶部导航 -->
    <div class="page-header">
      <div class="back-btn" @click="goBack">
        <span>← 返回</span>
      </div>
      <div class="page-title">装备市场</div>
      <div class="placeholder"></div>
    </div>

    <!-- 用户信息栏 -->
    <UserInfoBar />

    <!-- 分类筛选 -->
    <div class="category-filter">
      <div 
        v-for="(category, index) in categories" 
        :key="index"
        class="category-item"
        :class="{ active: activeCategory === index }"
        @click="selectCategory(index)"
      >
        {{ category.name }}
      </div>
    </div>

    <!-- 装备列表 -->
    <div class="equipment-list" v-if="!loading">
      <div 
        v-for="item in filteredItems" 
        :key="item.id"
        class="equipment-card"
        @click="showItemDetail(item)"
      >
        <div class="equipment-image">
          <img :src="getItemImage(item)" class="equipment-icon" />
          <div :class="['quality-badge', 'quality-' + (item.quality || 'common')]">
            {{ getQualityText(item.quality) }}
          </div>
        </div>
        <div class="equipment-info">
          <div :class="['equipment-name', 'quality-' + (item.quality || 'common')]">
            {{ item.name }}
          </div>
          <div class="equipment-type">{{ getTypeText(item.type) }}</div>
          <div v-if="item.attributes && item.attributes.length > 0" class="equipment-attributes">
            <div 
              v-for="(attr, idx) in item.attributes.slice(0, 2)" 
              :key="idx"
              class="attribute-item"
            >
              {{ attr.name }}: <span class="attribute-value">{{ attr.value }}</span>
            </div>
          </div>
          <div class="equipment-footer">
            <div class="equipment-price">
              <span class="price-value">{{ formatPrice(item.price) }}</span>
              <span class="price-unit">银两</span>
            </div>
            <button class="buy-btn" @click.stop="buyItem(item)">
              购买
            </button>
          </div>
        </div>
      </div>
      
      <div v-if="filteredItems.length === 0" class="empty-state">
        <text>暂无装备</text>
      </div>
    </div>

    <div v-else class="loading-state">
      <text>加载中...</text>
    </div>

    <!-- 装备详情弹框 -->
    <div v-if="showDetail" class="detail-modal" @click="closeDetail">
      <div class="modal-content" @click.stop v-if="selectedItem">
        <div class="modal-header">
          <div class="modal-title">{{ selectedItem.name }}</div>
          <div class="modal-close" @click="closeDetail">×</div>
        </div>
        <div class="modal-body">
          <div class="detail-image">
            <img :src="getItemImage(selectedItem)" class="detail-icon" />
          </div>
          <div class="detail-info">
            <div class="detail-type">{{ getTypeText(selectedItem.type) }}</div>
            <div class="detail-desc">{{ selectedItem.description || '暂无描述' }}</div>
            <div v-if="selectedItem.attributes && selectedItem.attributes.length > 0" class="detail-attributes">
              <div class="attributes-title">属性</div>
              <div 
                v-for="(attr, idx) in selectedItem.attributes" 
                :key="idx"
                class="attribute-row"
              >
                <span class="attr-name">{{ attr.name }}</span>
                <span class="attr-value">{{ attr.value }}</span>
              </div>
            </div>
            <div class="detail-price">
              <span class="price-label">价格：</span>
              <span class="price-value">{{ formatPrice(selectedItem.price) }}</span>
              <span class="price-unit">银两</span>
            </div>
            <div v-if="selectedItem.seller" class="detail-seller">
              <span class="seller-label">卖家：</span>
              <span class="seller-name">{{ selectedItem.seller }}</span>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeDetail">取消</button>
          <button class="confirm-buy-btn" @click="confirmBuy" :disabled="buying">
            {{ buying ? '购买中...' : '确认购买' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 全局底部导航栏 -->
    <CustomTabBar />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import api from '@/api'

export default {
  name: 'MarketEquipmentPage',
  data() {
    return {
      loading: true,
      activeCategory: 0,
      categories: [
        { name: '全部', type: 'all' },
        { name: '武器', type: 'weapon' },
        { name: '防具', type: 'armor' },
        { name: '饰品', type: 'accessory' }
      ],
      items: [],
      showDetail: false,
      selectedItem: null,
      buying: false
    }
  },
  computed: {
    filteredItems() {
      if (this.activeCategory === 0) {
        return this.items
      }
      const categoryType = this.categories[this.activeCategory].type
      return this.items.filter(item => item.type === categoryType || item.category === categoryType)
    }
  },
  mounted() {
    this.loadItems()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    selectCategory(index) {
      this.activeCategory = index
    },
    
    async loadItems() {
      this.loading = true
      try {
        // TODO: 根据实际后端接口调整
        const response = await api.post('/store/info', { 
          type: 'equipment',
          category: this.categories[this.activeCategory].type 
        })
        if (response && response.code === 1) {
          this.items = Array.isArray(response.data?.items) ? response.data.items : []
        } else {
          // 如果接口未实现，使用模拟数据
          this.items = this.getMockItems()
        }
      } catch (error) {
        console.error('加载装备列表失败:', error)
        this.items = this.getMockItems()
      } finally {
        this.loading = false
      }
    },
    
    getMockItems() {
      return [
        {
          id: 1,
          name: '玄铁重剑',
          description: '重剑无锋，大巧不工',
          type: 'weapon',
          quality: 'epic',
          price: 5000,
          seller: '铸剑山庄',
          attributes: [
            { name: '攻击力', value: '+350' },
            { name: '暴击率', value: '+15%' },
            { name: '耐久度', value: '100/100' }
          ]
        },
        {
          id: 2,
          name: '龙鳞护甲',
          description: '真龙鳞片打造，防御力惊人',
          type: 'armor',
          quality: 'legendary',
          price: 15000,
          seller: '铸剑山庄',
          attributes: [
            { name: '防御力', value: '+500' },
            { name: '生命值', value: '+2000' },
            { name: '魔法抗性', value: '+25%' }
          ]
        },
        {
          id: 3,
          name: '疾风之靴',
          description: '增加移动速度和闪避',
          type: 'accessory',
          quality: 'rare',
          price: 3000,
          seller: '神秘商人',
          attributes: [
            { name: '速度', value: '+100' },
            { name: '闪避', value: '+10%' }
          ]
        },
        {
          id: 4,
          name: '精铁长剑',
          description: '普通的精铁打造的长剑',
          type: 'weapon',
          quality: 'common',
          price: 500,
          seller: '铁匠铺',
          attributes: [
            { name: '攻击力', value: '+50' }
          ]
        }
      ]
    },
    
    getItemImage(item) {
      return item.icon || item.image || '/static/default-equipment.png'
    },
    
    getQualityText(quality) {
      const map = {
        'common': '普通',
        'uncommon': '优秀',
        'rare': '稀有',
        'epic': '史诗',
        'legendary': '传说'
      }
      return map[quality] || '普通'
    },
    
    getTypeText(type) {
      const map = {
        'weapon': '武器',
        'armor': '防具',
        'accessory': '饰品',
        'helmet': '头盔',
        'boots': '靴子'
      }
      return map[type] || type || '装备'
    },
    
    formatPrice(price) {
      if (!price) return '0'
      return price.toLocaleString()
    },
    
    showItemDetail(item) {
      this.selectedItem = item
      this.showDetail = true
    },
    
    closeDetail() {
      this.showDetail = false
      this.selectedItem = null
    },
    
    buyItem(item) {
      this.showItemDetail(item)
    },
    
    async confirmBuy() {
      if (!this.selectedItem || this.buying) return
      
      this.buying = true
      try {
        const response = await api.post('/store/exchange', {
          id: this.selectedItem.id,
          count: 1
        })
        if (response && response.code === 1) {
          uni.showToast({ title: '购买成功', icon: 'success' })
          this.closeDetail()
          // 重新加载列表
          this.loadItems()
        } else {
          uni.showToast({ title: response?.msg || '购买失败', icon: 'none' })
        }
      } catch (error) {
        console.error('购买失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.buying = false
      }
    }
  }
}
</script>

<style scoped>
.market-equipment-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding-bottom: 80px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-btn {
  font-size: 16px;
  color: #667eea;
  cursor: pointer;
  padding: 5px 10px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.placeholder {
  width: 60px;
}

/* 分类筛选 */
.category-filter {
  display: flex;
  gap: 10px;
  padding: 15px 20px;
  overflow-x: auto;
  background: rgba(255, 255, 255, 0.95);
  margin: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-item {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  background: #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  flex-shrink: 0;
}

.category-item.active {
  background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
  color: white;
  font-weight: 500;
}

/* 装备列表 */
.equipment-list {
  padding: 0 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.equipment-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 15px;
  display: flex;
  gap: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.equipment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.equipment-image {
  position: relative;
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.equipment-icon {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.quality-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: bold;
  color: white;
}

.quality-common { background: #9e9e9e; }
.quality-uncommon { background: #4caf50; }
.quality-rare { background: #2196f3; }
.quality-epic { background: #9c27b0; }
.quality-legendary { background: #ff9800; }

.equipment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.equipment-name {
  font-size: 16px;
  font-weight: bold;
}

.equipment-name.quality-common { color: #9e9e9e; }
.equipment-name.quality-uncommon { color: #4caf50; }
.equipment-name.quality-rare { color: #2196f3; }
.equipment-name.quality-epic { color: #9c27b0; }
.equipment-name.quality-legendary { color: #ff9800; }

.equipment-type {
  font-size: 12px;
  color: #999;
}

.equipment-attributes {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 4px;
}

.attribute-item {
  font-size: 12px;
  color: #666;
}

.attribute-value {
  color: #667eea;
  font-weight: 500;
}

.equipment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.equipment-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price-value {
  font-size: 18px;
  font-weight: bold;
  color: #ff9800;
}

.price-unit {
  font-size: 12px;
  color: #999;
}

.buy-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.buy-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

.empty-state, .loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 14px;
}

/* 详情弹框 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-content {
  width: 90%;
  max-width: 400px;
  max-height: 80vh;
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
  color: white;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.modal-close {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 24px;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.detail-image {
  text-align: center;
  margin-bottom: 20px;
}

.detail-icon {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  border: 2px solid #f0f0f0;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-type {
  font-size: 13px;
  color: #999;
  text-transform: uppercase;
}

.detail-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.detail-attributes {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-top: 8px;
}

.attributes-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.attribute-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  font-size: 13px;
}

.attr-name {
  color: #666;
}

.attr-value {
  color: #667eea;
  font-weight: 500;
}

.detail-price, .detail-seller {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.price-label, .seller-label {
  color: #999;
}

.price-value {
  color: #ff9800;
  font-weight: bold;
  font-size: 18px;
}

.seller-name {
  color: #667eea;
  font-weight: 500;
}

.modal-actions {
  display: flex;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn, .confirm-buy-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
}

.confirm-buy-btn {
  background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
  color: white;
}

.confirm-buy-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

.confirm-buy-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

